package com.xx.springboot.test.RabbitMQ.publishSubScripe;

import com.rabbitmq.client.*;
import com.xx.springboot.test.RabbitMQ.RabbitMQUtil;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created by xiaoxiunique on 2018-9-1.
 */
public class ReceiveLogs {

    private static final String EXCHANGE_NAME = "logs";

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = RabbitMQUtil.getConnection();

        Channel channel = connection.createChannel();

        // 定义交易所
        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");

        // 得到随机队列名称
        String queueName = channel.queueDeclare().getQueue();

        /**
         * 绑定队列 和 交易所
         */
        channel.queueBind(queueName, EXCHANGE_NAME, "");

        System.out.println("[*] Waiting for messages. ");

        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, "utf-8");
                System.out.println("Received : " + message);
            }
        };

        channel.basicConsume(queueName, true, consumer);

    }
}
